package com.kangyi.app.controller;

import com.kangyi.app.service.UserService;
import com.kangyi.app.service.impl.TokenBlacklistServiceImpl;
import com.kangyi.app.sms.SmsServer;
import com.kangyi.constant.JwtClaimsConstant;
import com.kangyi.constant.MessageConstant;
import com.kangyi.dto.*;
import com.kangyi.entity.User;
import com.kangyi.properties.JwtProperties;
import com.kangyi.result.PageResult;
import com.kangyi.result.Result;
import com.kangyi.utils.AuthUtil;
import com.kangyi.utils.JwtUtil;
import com.kangyi.vo.UserLoginVO;
import com.kangyi.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Blank
 * @version 1.0
 */
@RestController
@RequestMapping("/app/user")
@Api(tags = "用户相关接口")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private SmsServer smsServer;
    @Autowired
    private TokenBlacklistServiceImpl tokenBlacklistServiceImpl;

    @PostMapping("/login")
    @ApiOperation(value = "用户登录")
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO) {
        log.info("用户登录：{}", userLoginDTO);

        try {
            User user = userService.login(userLoginDTO);

            //登录成功后，生成jwt令牌
            Map<String, Object> claims = new HashMap<>();
            claims.put(JwtClaimsConstant.USER_ID, user.getId());
            String token = JwtUtil.createJWT(
                    jwtProperties.getUserSecretKey(),
                    jwtProperties.getUserTtl(),
                    claims);

            UserLoginVO userLoginVO = UserLoginVO.builder()
                    .id(user.getId())
                    .name(user.getName())
                    .headshot(user.getHeadshot())
                    .phone(user.getPhone())
                    .token(token)
                    .build();

            return Result.success(userLoginVO,"登录成功！");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @PostMapping("/register")
    @ApiOperation("注册")
    public Result register(@RequestBody UserDTO userDTO){
        log.info("注册:{}",userDTO);
        try {
            // 验证验证码
            boolean isValid = smsServer.verifyCode(userDTO.getPhone(), userDTO.getCode());
            if (!isValid) {
                return Result.error("验证码错误或已过期");
            }
            userService.register(userDTO);
            return Result.success("注册成功！");
        } catch (Exception e) {
            return Result.error("注册失败: " + e.getMessage());
        }
    }

    @PostMapping("/resetPassword")
    @ApiOperation("忘记密码")
    public Result resetPassword(@RequestBody ForgotPasswordDTO forgotPasswordDTO){
        log.info("忘记密码、修改：{}",forgotPasswordDTO);
        try {
            // 验证验证码
            boolean isValid = smsServer.verifyCode(forgotPasswordDTO.getPhone(), forgotPasswordDTO.getCode());
            if (!isValid) {
                return Result.error("验证码错误或已过期");
            }
            userService.resetPassword(forgotPasswordDTO);
            return Result.success("修改成功！");
        } catch (Exception e) {
            return Result.error("修改失败: " + MessageConstant.ROOT_ERROR);
        }
    }

    @PostMapping("/logout")
    @ApiOperation("退出")
    public Result<String> logout(HttpServletRequest request) {
        try {
            // 获取 Token
            String token = request.getHeader(jwtProperties.getUserTokenName());
            log.info("收到的 Token: {}", token);

            if (token == null || token.trim().isEmpty()) {
                return Result.error("Token 为空");
            }

            // 获取 jti
            String jti = JwtUtil.getJtiFromUserToken(jwtProperties.getUserSecretKey(), token);
            log.info("解析出的 jti: {}", jti);

            if (jti == null || jti.trim().isEmpty()) {
                return Result.error("Token 解析失败，jti 为空");
            }

            // 添加到黑名单
            tokenBlacklistServiceImpl.addToBlacklist(jti);
            log.info("Token 已加入黑名单: {}", jti);

            return Result.success("退出成功");
        } catch (Exception e) {
            log.error("退出登录失败: {}", e.getMessage(), e);
            return Result.error("退出登录失败: " + e.getMessage());
        }
    }

    @GetMapping("/info")
    @ApiOperation("查询用户个人信息")
    public Result<UserVO> infoUser(){
        log.info("查询用户");
        try {
            UserVO userVO = userService.inquiryUser();
            return Result.success(userVO,"查询成功！");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @PutMapping("/update")
    @ApiOperation("编辑用户信息")
    public Result update(@RequestBody UserEditDTO userEditDto){
        log.info("编辑用户信息：{}",userEditDto);
        try {
            AuthUtil.validateUserPermission(userEditDto.getId()); // 确保只能修改自己的信息
            userService.update(userEditDto);
            return Result.success("资料更新成功");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @GetMapping("/nursingHomeAppointments")
    @ApiOperation("获取养老院预约记录")
    public Result<PageResult> nursingHomeAppointments(NursingHomeAppointmentsDTO nursingHomeAppointmentsDTO){
        log.info("获取养老院预约记录:{}",nursingHomeAppointmentsDTO);
        try {
            PageResult pageResult = userService.nursingHomeAppointments(nursingHomeAppointmentsDTO);
            return Result.success(pageResult,"查询成功！");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @GetMapping("/charityRegistrations")
    @ApiOperation("获取公益活动报名记录")
    public Result<PageResult> charityRegistrations(CharityRegistrationsDTO charityRegistrationsDTO){
        log.info("获取公益活动报名记录:{}",charityRegistrationsDTO);
        try {
            PageResult pageResult = userService.charityRegistrations(charityRegistrationsDTO);
            return Result.success(pageResult,"查询成功！");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @GetMapping("/reviews")
    @ApiOperation("获取用户评价列表")
    public Result<PageResult> reviews(UserPageDTO userPageDTO){
        log.info("获取用户评价列表:{}",userPageDTO);
        try {
            PageResult pageResult = userService.reviews(userPageDTO);
            return Result.success(pageResult,"查询成功！");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @DeleteMapping("/deleteReview/{reviewId}")
    @ApiOperation("删除用户评价")
    public Result deleteReview(Integer reviewId){
        log.info("删除用户评价:{}",reviewId);
        try {
            userService.deleteReview(reviewId);
            return Result.success("删除成功！");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @GetMapping("/favorites")
    @ApiOperation("获取用户收藏列表")
    public Result<PageResult> favorites(UserPageDTO userPageDTO){
        log.info("获取用户收藏列表:{}",userPageDTO);
        try {
            PageResult pageResult = userService.favorites(userPageDTO);
            return Result.success(pageResult,"查询成功！");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
}
